package report

import (
	"context"
	"sort"
	"strconv"
	"strings"
	"time"

	"sale-admin/internal/app/web/service/common"
	"sale-admin/internal/models"

	"192.168.1.75/go-pkg/helper"
	"github.com/golang-module/carbon"
	"gorm.io/datatypes"
	"gorm.io/gorm"
)

type ReportEventService struct{}

func (re ReportEventService) EventList(ctx context.Context, db *gorm.DB, page, limit int) (data []models.MaEvent, count int64, err error) {
	tx := db.Table(models.MaEvent{}.TableName() + " as c")
	tx.Count(&count)
	var res = []models.MaEvent{}
	helper.Gorm{}.Paginate(tx, page, limit).
		Joins("left join " + models.MaEventQuestion{}.TableName() + " as q on q.id = c.event").
		Order("c.add_time desc").
		Select("c.*,q.content as event").
		Find(&res)

	// ShopName         string         `gorm:"-" json:"shop_name" json_old:"ShopName"`
	for _, v := range res {
		// 通过GRPC查询当前的用户ID对应的用户名称
		v.ShopName = "1"
	}

	return res, count, nil
}

// 添加
func (re ReportEventService) AddEvent(ctx context.Context, db *gorm.DB, merchantID, SalesID, RobotName, Date string,
	Event, EventType string, EeventDesc, AffectedTime, Location, userID string) (err error) {
	var InsertData models.MaEvent
	InsertData.ShopID = userID // 商户ID改成用户ID
	InsertData.Location = Location
	InsertData.SalesID = SalesID
	InsertData.RobotName = RobotName
	InsertData.Date = datatypes.Date(carbon.Parse(Date).ToStdTime())
	InsertData.Event = Event
	InsertData.EventType = EventType
	InsertData.EeventDesc = EeventDesc
	InsertData.AffectedTime = AffectedTime
	AffectedTimeSlice := strings.Split(strings.TrimSuffix(AffectedTime, "分钟"), "小时")
	hours, _ := strconv.Atoi(AffectedTimeSlice[0])
	minutes, _ := strconv.Atoi(AffectedTimeSlice[1])
	InsertData.AffectedTimeMill = (hours*60 + minutes) * 60 * 1000 //影响的运营时长毫秒数
	InsertData.AddTime = time.Now()
	db.Model(&models.MaEvent{}).Create(&InsertData)
	return
}

// 编辑运营事件
func (re ReportEventService) EditEvent(ctx context.Context, db *gorm.DB, merchantID, SalesID, RobotName, Date string,
	Event, EventType string, EeventDesc, AffectedTime, Location, userID string, ID int) (err error) {
	var InsertData models.MaEvent
	InsertData.ShopID = userID // 商户ID改成用户ID
	InsertData.Location = Location
	InsertData.SalesID = SalesID
	InsertData.RobotName = RobotName
	InsertData.Date = datatypes.Date(carbon.Parse(Date).ToStdTime())
	InsertData.Event = Event
	InsertData.EventType = EventType
	InsertData.EeventDesc = EeventDesc
	InsertData.AffectedTime = AffectedTime
	AffectedTimeSlice := strings.Split(strings.TrimSuffix(AffectedTime, "分钟"), "小时")
	hours, _ := strconv.Atoi(AffectedTimeSlice[0])
	minutes, _ := strconv.Atoi(AffectedTimeSlice[1])
	InsertData.AffectedTimeMill = (hours*60 + minutes) * 60 * 1000 //影响的运营时长毫秒数
	InsertData.AddTime = time.Now()
	// db.Model(&models.MaEvent{}).Create(&InsertData)
	db.Model(&models.MaEvent{}).Where("id = ?", ID).Updates(&InsertData)
	return
}

// 删除运营事件
func (re ReportEventService) DelEvent(ctx context.Context, db *gorm.DB, ID int) (err error) {
	db.Model(&models.MaEvent{}).Where("id = ?", ID).Delete(&models.MaEvent{})
	return
}

type EventDescInfo struct {
	Date       string `json:"date"`
	TotalEvent int    `json:"total_event"`
	EventType  string `json:"event_type"`
	Name       string `json:"name"`
}
type EventDescReturn struct {
	Date string          `json:"date"`
	Data []EventDescInfo `json:"data"`
}

type TopEventList struct {
	TotalEvent    int    `json:"total_event"`
	EventType     string `json:"event_type"`
	Name          string `json:"name"`
	EventQuestion string `json:"event_question"`
}

func (re ReportEventService) EventDesc(ctx context.Context, db *gorm.DB, merchantID, SalesID, StartTime, EndTime string,
	EventType string, shopIDList []string) (data []EventDescReturn, top []TopEventList, count int, err error) {
	var where string
	tx := db.Table(models.MaEvent{}.TableName() + " as c")
	if SalesID != "" {
		var saleString string
		for _, v := range strings.Split(SalesID, ",") {
			saleString += " \"" + v + "\","
		}
		saleString = strings.TrimSuffix(saleString, ",")
		where += " and c.sales_id in (" + saleString + ")"
	}
	if StartTime != "" && EndTime != "" {
		where += " and c.add_time between '" + StartTime + "' and '" + EndTime + " 23:59:59'"
	}
	if EventType != "" && EventType != "0" {
		where += " and c.event_type = " + EventType
	}
	//商户
	merchantIDs, err1 := common.Order{}.GetMerchantChildren(ctx, merchantID, shopIDList)
	if err1 != nil {
		err = err1
		return
	}
	where += " and c.shop_id in (" + strings.Join(merchantIDs, ",") + ")"
	where = strings.TrimPrefix(where, " and ")
	var Res = []EventDescInfo{}
	field := "date_format(c.date, '%Y-%m-%d') as date, count(c.id) AS total_event, c.event_type, t.name"
	tx.Joins("left join " + models.MaEventType{}.TableName() + " as t on t.id = c.event_type").
		Where(where).
		Group("date,event_type").
		Order("total_event asc").
		Select(field).
		Find(&Res)

	var DateResMap = make(map[string][]EventDescInfo)
	for _, v := range Res {
		DateResMap[v.Date] = append(DateResMap[v.Date], v)
	}
	var DateResSlice = []EventDescReturn{}
	for date, data := range DateResMap {
		DateResSlice = append(DateResSlice, struct {
			Date string          `json:"date"`
			Data []EventDescInfo `json:"data"`
		}{
			Date: date,
			Data: data,
		})
	}
	sort.Slice(DateResSlice, func(i, j int) bool {
		return DateResSlice[i].Date < DateResSlice[j].Date
	})
	count = len(DateResSlice)
	var TopEventList = []TopEventList{}
	db.Table(models.MaEvent{}.TableName() + " as c").
		Joins("left join " + models.MaEventType{}.TableName() + " as t on t.id = c.event_type").
		Joins("left join " + models.MaEventQuestion{}.TableName() + " as q on q.id = c.event").
		Where(where).
		Select("count(c.id) AS total_event, c.event_type, t.name, q.content as event_question").
		Group("event_type").
		Order("total_event asc").
		Find(&TopEventList)
	return DateResSlice, TopEventList, count, nil
}
